<template>
  <a-card :bordered="false">
    <div class="table-operator">
      <a-row>
        <a-button type="primary" icon="plus" v-if="hasPerm('TD_Receiving.Add')" @click="hanldleAdd()">新建</a-button>
        <a-button
          type="primary"
          icon="minus"
          v-if="hasPerm('TD_Receiving.Delete')"
          @click="handleDelete(selectedRowKeys)"
          :disabled="!hasSelected()"
          :loading="loading"
        >
          删除
        </a-button>
        <a-button type="primary" icon="redo" @click="getDataList()">刷新</a-button>
        <a-radio-group
          default-value="desc"
          @change="getDataList()"
          button-style="solid"
          v-model="sorter.order"
          style="margin-right: 10px;"
        >
          <a-radio-button value="asc">
            <a-icon type="arrow-up" />
            正序
          </a-radio-button>
          <a-radio-button value="desc">
            <a-icon type="arrow-down" />
            倒序
          </a-radio-button>
        </a-radio-group>
        <a-radio-group
          v-model="ReceStatus"
          button-style="solid"
          @change="
            () => {
              this.pagination.current = 1
              this.getDataList()
            }
          "
        >
          <a-radio-button :value="null">全部</a-radio-button>
          <a-radio-button :value="0">待审核</a-radio-button>
          <a-radio-button :value="1">已审核</a-radio-button>
          <!-- <a-radio-button :value="2">已取消</a-radio-button> -->
          <a-radio-button :value="3">上架中</a-radio-button>
          <!-- <a-radio-button :value="6">待复核</a-radio-button> -->
          <a-radio-button :value="4">已完成</a-radio-button>
          <a-radio-button :value="5">作废</a-radio-button>
        </a-radio-group>
      </a-row>
    </div>

    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="10">
          <a-col :md="4" :sm="24">
            <a-form-item>
              <a-input v-model="Code" placeholder="收货单号" allowClear />
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="24">
            <a-form-item>
              <a-select v-model="Type" allowClear>
                <a-select-option
                  v-for="(item, index) in TypeList"
                  :value="item.DicValue"
                  :key="index"
                >{{ item.DicName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="24">
            <a-form-item>
              <!-- <a-date-picker format="YYYY-MM-DD" v-model="queryParam.RecTime" placeholder="收货日期" /> -->
              <a-form-item>
                <a-range-picker @change="onChange" v-model="date" />
              </a-form-item>
            </a-form-item>
          </a-col>
          <a-col :md="2" :sm="15">
            <a-form-item>
              <a-input v-model="RealName" placeholder="制单人" allowClear />
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="15">
            <a-form-item>
              <a-input v-model="Name" placeholder="物品名称/编号/规格" allowClear />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-button
              type="primary"
              @click="
                () => {
                  this.pagination.current = 1
                  this.getDataList()
                }
              "
            >
              查询
            </a-button>
            <a-button style="margin-left: 8px" @click="react">重置</a-button>
            <!--            <a-button style='margin-left: 8px' @click='saoma'>扫码枪</a-button>-->
          </a-col>
        </a-row>
      </a-form>
    </div>

    <a-table
      ref="table"
      :scroll="{ y: 560 }"
      :columns="columns"
      :rowKey="row => row.Id"
      :dataSource="data"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, columnWidth: '40px' }"
      :bordered="true"
      size="small"
      :rowClassName="rowClassName"
    >
      <template slot="Type" slot-scope="text">
        <enum-name code="ReceiveType" :value="text"></enum-name>
      </template>
      <template slot="Status" slot-scope="text, record, index">
        <span>{{ Status(text) }}</span>
      </template>

      <template slot="ToReviewStatus" slot-scope="text">
        <a-tag color="blue" v-if="text == 0">
          正常
        </a-tag>
        <a-tag color="red" v-if="text == 1">
          异常
        </a-tag>
      </template>
      <!-- <template slot="Status" slot-scope="text, record">
        <a-tag v-if="record.Status === 0" color="blue">编制中</a-tag>
        <a-tag v-else-if="record.Status === 1" color="blue">已确认</a-tag>
        <a-tag v-else-if="record.Status === 3" color="green">上架中</a-tag>
        <a-tag v-else-if="record.Status === 4" color="red">已完成</a-tag>
        <a-tag v-else color="blue">编制中</a-tag>
      </template> -->

      <span slot="action" slot-scope="text, record">
        <template>
          <span v-if="hasPerm('TD_Receiving.View')">
            <a v-if="record.Status != 0" @click="handleEdit(record.Id, true, '查看')">查看</a>
            <a-divider v-if="record.Status != 0" type="vertical" />
          </span>
          <span v-if="hasPerm('TD_Receiving.Edit')">
            <a v-if="record.Status == 0" @click="handleEdit(record.Id, true, '编辑')">编辑</a>
            <a-divider v-if="record.Status == 0" type="vertical" />
          </span>
          <span v-if="hasPerm('TD_Receiving.Delete')">
            <a v-if="record.Status == 0" @click="handleDelete([record.Id])">删除</a>
            <a-divider v-if="record.Status == 0" type="vertical" />
          </span>
          <span v-if="hasPerm('TD_Receiving.Auditing')">
            <a v-if="record.Status === 0" @click="handleApproval(record.Id)">审核</a>
            <a-divider v-if="record.Status == 0" type="vertical" />
          </span>

          <span>
            <a-popconfirm
              title="请选择打印的类型"
              cancel-text="打印小票"
              ok-text="打印A4纸"
              @confirm="confirm"
              @cancel="cancel"
            >
              <a v-if="record.Status != 0 && record.Status != 5" @click="PrintReceipt(record.Id)">打印</a></a-popconfirm
              >
            <a-divider v-if="record.Status != 0 && record.Status != 5" type="vertical" />
          </span>
          <span>
            <a v-if="record.Status === 1" @click="startWork(record.Id)">开始上架</a>
            <a-divider v-if="record.Status == 1" type="vertical" />
          </span>
          <span v-if="hasPerm('TD_Receiving.print')">
            <a v-if="record.Status != 0 && record.Status != 5" @click="PrintCode(record.Id)">打码</a>
            <a-divider v-if="record.Status != 0 && record.Status != 5" type="vertical" />
          </span>
          <span v-if="hasPerm('TD_Receiving.invalid')">
            <a v-if="record.Status == 1 || record.Status == 3" @click="cancellation(record.Id)">作废</a>
          </span>
          <!-- <a v-if="record.Status !==0" @click="PrintreceiptNote(record.Id)">打印</a> -->

          <!-- <span v-if="record.Type !== 'HalfReceiving'"> </span>
          <span v-if="hasPerm('TD_Receiving.invalid')">
            <a-divider v-if="record.Status != 0 && record.Status != 5 && record.Status != 4" type="vertical" />
            <a v-if="record.Status != 0 && record.Status != 5 && record.Status != 4" @click="cancellation(record.Id)"
              >作废</a
            >
          </span>

          <span v-if="record.Status == 6">
            <a-divider type="vertical" />
            <a @click="handleSub(record.Id, '复核')">复核</a>
          </span> -->
          <!-- <span v-if="record.Status == 3">
            <a-divider type="vertical" />
            <a @click="handleSub(record.Id)">提交</a>
          </span> -->
        </template>
      </span>
      <template slot="dataIndex" slot-scope="text, record, index">
        <span>{{ (pagination.current - 1) * pagination.pageSize + index + 1 }}</span>
      </template>
    </a-table>
    <a-modal title="扫码枪" :visible="showSweepCode" @ok="handleOk" @cancel="showSweepCode = false">
      <a-input ref="showSweep" v-model="showSweepValue" @keydown="handleOk" allowClear></a-input>
    </a-modal>
    <edit-form ref="editForm" :disabled="disabled" :parentObj="this"></edit-form>
    <in-storage ref="inStorage" :parentObj="this"></in-storage>
    <EditFormToexamine ref="editFormToexamine" :parentObj="this" :disabled="disabled"></EditFormToexamine>
    <ReceivingPrint ref="receivingPrint" :parentObj="this"></ReceivingPrint>
    <PrintCode ref="PrintCode" :parentObj="this"></PrintCode>
    <ReceiptNote ref="receiptNote" :parentObj="this"></ReceiptNote>
  </a-card>
</template>

<script>
import moment from 'moment'
import EditForm from './EditForm'
import EditFormToexamine from './EditFormToexamine'
import ReceivingPrint from './ReceivingPrint'
import PrintCode from './PrintCode'
import ReceiptNote from './ReceiptNote'

const filterDate = (value, row, index) => {
  if (value) {
    return moment(value).format('YYYY-MM-DD')
  } else {
    return ' '
  }
}
const columns = [
  {
    title: '序号',
    align: 'center',
    width: '50px',
    scopedSlots: { customRender: 'dataIndex' }
  },
  { title: '收货单号', dataIndex: 'Code', width: '100px', ellipsis: true },
  {
    title: '收货日期',
    dataIndex: 'RecTime',
    customRender: filterDate,
    width: '100px',
    scopedSlots: { customRender: 'RecTime' }
  },
  { title: '收货类型', dataIndex: 'RType', scopedSlots: { customRender: 'RType' }, width: '100px', ellipsis: true },
  { title: '制单人', dataIndex: 'RealName', width: '80px' },
  { title: '收货数量', dataIndex: 'TotalNum', align: 'right', width: '80px' },
  { title: '入库数量', dataIndex: 'InNum', align: 'right', width: '80px' },
  { title: '状态', dataIndex: 'Status', scopedSlots: { customRender: 'Status' }, width: '80px' },
  { title: '入库状态', dataIndex: 'ToReviewStatus', width: '100px', scopedSlots: { customRender: 'ToReviewStatus' } },
  { title: '操作', dataIndex: 'action', scopedSlots: { customRender: 'action' }, width: '200px' }
]

export default {
  components: {
    EditForm,
    EditFormToexamine,
    ReceivingPrint,
    PrintCode,
    ReceiptNote
  },
  created () {
    this.getDataList()

    this.TypeList = []
    this.$http.post('/Base_BasicData/Base_DictionaryMain/GetTheDataByDicKey', {
      Condition: 'DicKey',
      Keyword: 'ReceiveType'
    }).then(resJson => {
      this.loading = false
      this.TypeList = resJson.Data.DictionaryDetailsList
    })
  },
  mounted () {
  },
  data () {
    return {
      ReceStatus: null,
      Code: '',
      Type: '',
      RealName: '',
      Name: '',
      TypeList: [],
      ReceDate: '',
      data: [],
      pagination: {
        current: 1,
        pageSize: 25,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面啊可以通过下拉框进行选择
        showSizeChanger: true,
        onShowSizeChange: (current, pageSize) => (this.pageSize = pageSize),
        defaultCurrent: 1,
        onChange: this.onPageChange.bind(this)
      },
      date: [],
      filters: {},
      sorter: { field: 'CreateTime', order: 'desc' },
      loading: false,
      columns,
      queryParam: [],
      selectedRowKeys: [],
      disabled: false,
      visible: null,
      visibles: false,
      pid: '',
      showSweepCode: false,
      showSweepValue: ''
    }
  },
  methods: {
    // (record, index) => (record.ToReviewStatus == 1 ? 'yichang' : '')
    rowClassName (record) {
      if (record.Status == 5) {
        return 'redrow'
      }
      if (record.ToReviewStatus == 1) {
        return 'yichang'
      }
    },
    handleSub (id, tit) {
      if (tit) {
        this.disabled = true
        this.$refs.editFormToexamine.openForm(id, '复核')
      } else {
        this.disabled = true
        this.$refs.editFormToexamine.openForm(id, '提交')
      }
    },
    saoma () {
      this.showSweepCode = true
      setTimeout(() => {
        this.$refs.showSweep.focus()
      }, 100)
    },
    handleOk (e) {
      if (e.keyCode == 13 || e.keyCode == undefined) {
        if (this.showSweepValue.split(',')[1]) {
          this.$refs.editForm.openForm(this.showSweepValue.split(',')[1], '查看')
        } else this.$message.error('请填写正确的扫码枪编号')
      }
    },
    cancellation (id) {
      // // 作废
      // this.$confirm({
      //   title: '确认作废吗?',
      //   onOk: () => {
      //     this.$http.post('/TD/TD_Receiving/CancelReceivingData?Id=' + id).then(res => {
      //       if (res.Success) {
      //         this.$message.success('操作成功!')
      //
      //         this.getDataList()
      //       } else {
      //         this.$message.error(res.Msg)
      //       }
      //     })
      //   }
      // })
      this.$confirm('确认作废吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return new Promise((resolve, reject) => {
          this.$http.post('/TD/TD_Receiving/CancelReceivingData?Id=' + id).then(res => {
            console.log(res)
            if (res.Success) {
              this.$message.success('开始作业成功')
              this.getDataList()
            } else {
              this.$message.error(res.Msg)
            }
          })
        }).catch(() => console.log('Oops errors!'))
      })
    },
    onPageChange (current) {
      this.pagination.current = current
    },
    react () {
      this.ReceStatus = null
      this.Code = ''
      this.Type = ''
      this.RealName = ''
      this.ReceDate = ''
      this.Name = ''
      this.queryParam = []
      this.pagination.current = 1
      this.pagination.pageSize = 25
      this.date = []
      this.getDataList()
    },

    PrintCode (id) {
      this.$refs.PrintCode.open(id, '打印成品码')
    },
    startWork (id) {
      // this.$confirm({
      //   title: '确认开始上架吗?',
      //   onOk: () => {
      //     this.$http.post('/TD/TD_Receiving/SaveStartJob?idIn=' + id).then(res => {
      //       console.log(res)
      //       if (res.Success) {
      //         this.$message.success('开始作业成功')
      //         this.getDataList()
      //       } else {
      //         this.$message.error(res.Msg)
      //       }
      //     })
      //   }
      // })
      this.$confirm('确认开始上架吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return new Promise((resolve, reject) => {
          this.$http.post('/TD/TD_Receiving/SaveStartJob?idIn=' + id).then(res => {
            console.log(res)
            if (res.Success) {
              this.$message.success('开始作业成功')
              this.getDataList()
            } else {
              this.$message.error(res.Msg)
            }
          })
        }).catch(() => console.log('Oops errors!'))
      })
    },
    handleTableChange (pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }
      this.getDataList()
    },
    Status (text) {
      var str = ''
      if (text == 0) {
        str = '待审核'
      } else if (text == 1) {
        str = '已审核'
      } else if (text == 3) {
        str = '上架中'
      } else if (text == 4) {
        str = '已完成'
      } else if (text == 5) {
        str = '作废'
      }
      return str
    },
    disabledDate (current) {
      return current && current > moment().endOf(0, 'day')
    },
    PrintreceiptNote (id) {
      this.$refs.receiptNote.openDrawer(id, '收货单小票')
    },
    getDataList () {
      this.selectedRowKeys = []
      // if (this.queryParam.RecTime && this.queryParam.RecTime != '')
      //   console.log(this.queryParam.RecTime);
      this.queryParam = [{ Condition: 'Code', Keyword: this.Code }, {
        Condition: 'ReceStatus',
        Keyword: this.ReceStatus
      }, { Condition: 'Type', Keyword: this.Type }, {
        Condition: 'RealName',
        Keyword: this.RealName
      }, { Condition: 'Name', Keyword: this.Name }, { Condition: 'ReceDate', Keyword: this.ReceDate }]
      this.loading = true
      this.$http
        .post('/TD/TD_Receiving/GetReceivingDataList', {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: 'UpdateTime',
          SortType: this.sorter.order,
          Search: this.queryParam,
          ...this.filters
        })
        .then(resJson => {
          this.loading = false
          this.data = resJson.Data
          if (this.data) {
            const pagination = { ...this.pagination }
            pagination.total = resJson.Total
            this.pagination = pagination
          }
          this.$nextTick(() => {
            if (this.data) {
              this.data.forEach((item, index) => {
                item.TotalNum = item.TotalNum + ''
                item.TotalNum = item.TotalNum.replace(/[^\d.]/g, '') // 清除“数字”和“.”以外的字符
                item.TotalNum = item.TotalNum.replace(/\.{2,}/g, '.') // 只保留第一个. 清除多余的
                item.TotalNum = item.TotalNum.replace('.', '$#$')
                  .replace(/\./g, '')
                  .replace('$#$', '.')
                item.TotalNum = item.TotalNum.replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/, '$1$2.$3') // 只能输入两个小数

                item.InNum = item.InNum + ''
                item.InNum = item.InNum.replace(/[^\d.]/g, '') // 清除“数字”和“.”以外的字符
                item.InNum = item.InNum.replace(/\.{2,}/g, '.') // 只保留第一个. 清除多余的
                item.InNum = item.InNum.replace('.', '$#$')
                  .replace(/\./g, '')
                  .replace('$#$', '.')
                item.InNum = item.InNum.replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/, '$1$2.$3') // 只能输入两个小数
                if (this.$refs['red' + index]) {
                  this.$refs['red' + index].parentNode.parentNode.style = 'color:red'
                }
              })
            }
            console.log(this.data)
            console.log(this.$refs.red)
          })
        })
    },
    onOrderTimeChange (dates, dateStrings) {
      this.queryParam.StartDate = dateStrings[0]
      this.queryParam.EndDate = dateStrings[1]
    },
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    hasSelected () {
      return this.selectedRowKeys.length > 0
    },
    hanldleAdd () {
      this.disabled = false
      this.$refs.editForm.openForm()
    },
    onChange (a, b) {
      console.log(a)
      console.log(b)
      // this.StartDate = b[0]
      // this.EndDate = b[1]
      this.ReceDate = b[0] + ',' + b[1]
    },
    /// 打印收货单
    PrintReceipt (id, index) {
      this.pid = id
      this.visible = index
      this.visibles = true
      // this.$refs.receivingPrint.openDrawer(id, '打印收货单')
    },
    confirm () {
      this.$refs.receivingPrint.openDrawer(this.pid, '打印收货单')
    },
    cancel () {
      this.$refs.receiptNote.openDrawer(this.pid, '收货单小票')
    },
    handleEdit (id, flag, tit) {
      this.disabled = flag
      console.log(id)
      if (tit == '查看') {
        this.$refs.editForm.openForm(id, '查看')
      } else {
        this.$refs.editForm.openForm(id, '编辑')
      }
    },
    handleApproval (id) {
      this.disabled = true
      this.$refs.editForm.openForm(id, '审核')
    },
    handleInStorage (id) {
      this.$refs.inStorage.openReceivingForm(id)
    },

    timeFormat (val) {
      // 时间格式化函数
      return moment(val).format('YYYY-MM-DD') /// HH:mm 时分秒
    },
    handleDelete (ids) {
      this.$confirm('确认删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return new Promise((resolve, reject) => {
          this.$http.post('/TD/TD_Receiving/DeleteData', ids).then(resJson => {
            resolve()

            if (resJson.Success) {
              this.$message.success('操作成功!')

              this.getDataList()
            } else {
              this.$message.error(resJson.Msg)
            }
          })
        }).catch(() => console.log('Oops errors!'))
      })
    }
  }
}
</script>
<style lang='less' scoped>
/deep/ .redrow {
  color: red;
}

/deep/ .yichang {
  background: #fbf2f2;
  // color:#fff;
  // text-decoration:underline
}
</style>
